package com.nut.lmsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nut.lmsc.api.req.ClientLoginReq;
import com.nut.lmsc.api.req.MemberQueryReq;
import com.nut.lmsc.common.FailMessage;
import com.nut.lmsc.common.Result;
import com.nut.lmsc.entity.Member;
import com.nut.lmsc.interceptor.JwtTokenUtil;
import com.nut.lmsc.interceptor.ClientJwt;
import com.nut.lmsc.interceptor.MerchantJwt;
import com.nut.lmsc.jbb.JbbService;
import com.nut.lmsc.mapper.MemberCouponMapper;
import com.nut.lmsc.mapper.MemberMapper;
import com.nut.lmsc.service.MemberCouponService;
import com.nut.lmsc.service.MemberService;
import com.nut.lmsc.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private JbbService jbbService;

    @Autowired
    private MemberCouponService memberCouponService;

    @Autowired
    private MemberCouponMapper memberCouponMapper;

    @Override
    public Result<IPage<Member>> listPage(MemberQueryReq req) {
        IPage<Member> list = memberMapper.listPage(req.newPage(), req.getName(), req.getMobile(), req.getStatus());
        return Result.ok(list);
    }

    @Override
    public Result<Member> getById(Long memberId) {

        Member member = memberMapper.selectById(memberId);
        if (member == null) {
            return Result.fail("找不到人员信息");
        }

        Integer count = memberCouponMapper.selectCountByMemberId(memberId);
        member.setCouponCount(count);

        return Result.ok(member);
    }

    @Override
    public Result add(Member member) {

        String mobile = member.getMobile();
        if (StringTool.isEmpty(mobile)) {
            return Result.fail("请输入手机号");
        }

        mobile = mobile.trim();

        member.setMobile(mobile);
        if (mobile.length() != 11) {
            return Result.fail("手机号错误");
        }

        // 检查手机号是否已注册
        Integer count = memberMapper.selectCount(new LambdaQueryWrapper<Member>().
                eq(Member::getMobile, mobile));
        if (count > 0) {
            log.error("mobile_has_registered,mobile={}", mobile);
            return Result.fail(FailMessage.AUTH_MOBILE_REGISTERED);
        }

        Long id = IdUtil.getMemberId();
        member.setId(id);

        memberMapper.insert(member);
        return Result.ok();
    }

    @Override
    public Result updateById(Member member) {

        String mobile = member.getMobile();
        if (StringTool.isNotEmpty(mobile)) {

            // 更改手机号
            mobile = mobile.trim();
            member.setMobile(mobile);
            if (mobile.length() != 11) {
                return Result.fail("手机号错误");
            }

            // 检查手机号是否已注册
            List<Member> list = memberMapper.selectList(new LambdaQueryWrapper<Member>().
                    eq(Member::getMobile, mobile));

            int size = list.size();
            if (size == 1) {
                // 判断是不是更新会员的手机号
                if (!list.get(0).getId().equals(member.getId())) {
                    return Result.fail("该手机号已存在");
                }
            } else if (size > 1) {
                return Result.fail("系统中已存在多个该手机号");
            }

        }

        //不改手机号
        member.setMobile(null);

        memberMapper.updateById(member);
        return Result.ok();
    }


    @Override
    public Result deleteByIds(Set<Serializable> ids) {

        for (Serializable id : ids) {
            memberMapper.deleteMember(id);
        }
        return Result.ok();
    }

    @Override
    public Result<String> clientLogin(ClientLoginReq req) {

        if (SpringUtil.isProd()) {
            Boolean check = jbbService.smsCheck(req.getMobile(), req.getCode());
            if (!check) {
                return Result.fail("短信验证码不对");
            }
        }

        String mobile = req.getMobile();

        Member member = memberMapper.selectByMobile(mobile);

        if (member == null) {
            member = new Member();
            member.setId(IdUtil.getMemberId());
            member.setStatus(0);
            member.setBalance(0);
            member.setName(mobile);
            member.setMobile(mobile);
            memberMapper.insert(member);
        }

        if (member.getStatus() == 1) {
            return Result.fail("该账号已被冻结");
        }

        String upperMobile = jbbService.userUpper(mobile);
        if (upperMobile != null) {
            Member update = new Member();
            update.setId(member.getId());
            update.setUpperMobile(upperMobile);
            memberMapper.updateById(update);
        }

        //初始化我的代金券， 之前别人送给我的
        memberCouponService.initCoupon(member.getId(), mobile);

        ClientJwt clientJwt = new ClientJwt();
        clientJwt.setMobile(mobile);
        clientJwt.setMemberId(member.getId());
        clientJwt.setShopId(member.getShopId());
        clientJwt.setUpperMobile(upperMobile);

        String clientToken = JwtTokenUtil.createClientToken(clientJwt);

        return Result.ok(clientToken);
    }

    @Override
    public Result<String> merchantLogin(ClientLoginReq req) {

        if (SpringUtil.isProd()) {
            Boolean check = jbbService.smsCheck(req.getMobile(), req.getCode());
            if (!check) {
                return Result.fail("短信验证码不对");
            }
        }

        String mobile = req.getMobile();

        Member member = memberMapper.selectByMobile(mobile);
        if (member == null) {
            return Result.fail("帐号不存在");
        }
        if (member.getStatus() == 1) {
            return Result.fail("该账号已被冻结");
        }

        if (SpringUtil.isProd()) {
            Boolean check = jbbService.userCheck(mobile);
            if (!check) {
                return Result.fail("您没有入驻资格");
            }
        }

        String upperMobile = jbbService.userUpper(mobile);
        if (upperMobile != null) {
            Member update = new Member();
            update.setId(member.getId());
            update.setUpperMobile(upperMobile);
            memberMapper.updateById(update);
        }

        MerchantJwt merchantJwt = new MerchantJwt();
        merchantJwt.setMobile(mobile);
        merchantJwt.setMemberId(member.getId());
        merchantJwt.setShopId(member.getShopId());

        String merchantToken = JwtTokenUtil.createMerchantToken(merchantJwt);
        return Result.ok(merchantToken);
    }

}